package top.healthylife.gateway.platform.fpd.api.api.fpd;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import top.healthylife.basics.utils.exception.BusinessException;
import top.healthylife.basics.utils.utils.R;
import top.healthylife.basics.utils.utils.SystemThreadLocal;
import top.healthylife.gateway.core.service.ParentFace;
import top.healthylife.gateway.core.util.SystemConfigUtils;
import top.healthylife.gateway.dto.annotation.ApiServiceExplain;
import top.healthylife.gateway.platform.fpd.api.config.SystemConfig;
import top.healthylife.gateway.platform.fpd.dto.userinfo.req.FpdReqUserInfoDetailsDto;
import top.healthylife.gateway.platform.fpd.dto.userinfo.res.FpdResUserInfoDetailsDto;
import top.heathylife.gateway.common.cons.SystemCons;
import top.heathylife.gateway.common.po.RecordRequestInfo;


/**
 * @author : GaoZeXi
 * @date 2021/6/1 17:23
 */
@Slf4j
@Service
@ApiServiceExplain(price = 0, apiName = "用户信息准入查询", info = "根据用户信息查询用户信息详情")
@AllArgsConstructor
public class FpdUserInfoDetailsApi implements ParentFace<FpdReqUserInfoDetailsDto, FpdResUserInfoDetailsDto> {

    RestTemplate restTemplate;

    static String URL = "http://%s/userInfo/query";

    /**
     * 1.数据源名称
     * 2.接口名称
     * 3.数据
     * @param t 字段说明
     * @return FpdResUserInfoDetailsDto
     */

    @Override
    public FpdResUserInfoDetailsDto execute(FpdReqUserInfoDetailsDto t) {
        SystemConfig baseConfig = (SystemConfig) SystemConfigUtils.get();
        String serviceName = baseConfig.getServiceName();
        try {
            //记录请求信息
            String format = String.format(URL, serviceName);
            RecordRequestInfo.recordRequest(format, JSONUtil.toJsonStr(t), null, "post(内部RestTemplate)");
            R<?> r = restTemplate.postForObject(format, t, R.class);
            //记录三方元数据
            SystemThreadLocal.set(SystemCons.ORIGIN_DATA, JSONObject.toJSONString(r));
            if (r == null) {
                throw new BusinessException("发票贷服务接口响应异常");
            }
            int code = r.getCode();
            if (code != 0) {
                throw new BusinessException(r.getMsg());
            }
            Object data = r.getData();
            if (data == null) {
                log.info("发票贷数据返回为空");
                return new FpdResUserInfoDetailsDto();
            }
            String dataJson = JSONObject.toJSONString(data);
            log.info("发票贷数据返回:{}", dataJson);
            return JSONObject.parseObject(dataJson, FpdResUserInfoDetailsDto.class);
        } catch (Exception exception) {
            log.error("发票贷服务接口响应异常:{}", exception.getMessage());
            throw new BusinessException("发票贷服务接口响应异常:{}", exception.getMessage());
        }
    }


}
